﻿using DotNetMVC.OA.IBLL;
using DotNetMVC.OA.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DotNetMVC.OA.BLL
{
    public partial class UserInfoService : BaseService<UserInfo>, IUserInfoService
    {
        public IQueryable<UserInfo> LoagPageData(Model.Param.UserQueryParam userQueryParam)
        {
            short normalFlag = (short)Model.Enum.DelFlagEnum.Normal;
            var temp = DbSession.UserInfoDal.GetEntities(u => u.DelFlag == normalFlag);

            //过滤用户名
            if (!string.IsNullOrEmpty(userQueryParam.SchName))
            {
                temp = temp.Where(u => u.UName.Contains(userQueryParam.SchName));
            }
            //过滤备注
            if (!string.IsNullOrEmpty(userQueryParam.SchRemark))
            {
                temp = temp.Where(u => u.Remark.Contains(userQueryParam.SchRemark));
            }
            userQueryParam.Total = temp.Count();
            //分页
            return temp.OrderBy(u => u.ID)
                .Skip(userQueryParam.PageSize * (userQueryParam.PageIndex - 1))
                .Take(userQueryParam.PageSize);

        }

        /// <summary>
        /// 设置角色
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="roleIds"></param>
        /// <returns></returns>
        public bool SetRole(long userId, List<long> roleIds)
        {
            short delFlagNormal = (short)Model.Enum.DelFlagEnum.Normal;
            //获取用户所有角色
            var rURs = DbSession.R_UserInfo_RoleInfoDal.GetEntities(rUR => rUR.UserInfoID == userId && rUR.DelFlag == delFlagNormal);
            //遍历删除原有角色
            foreach (var rUR in rURs)
            {
                DbSession.R_UserInfo_RoleInfoDal.Delete(rUR);
            }

            //获取选中权限
            var allRoles = DbSession.RoleInfoDal.GetEntities(r => roleIds.Contains(r.ID));
            foreach (var roleInfo in allRoles)
            {
                R_UserInfo_RoleInfo model = new R_UserInfo_RoleInfo();
                model.UserInfoID = userId;
                model.RoleInfoID = roleInfo.ID;
                //添加到用户角色关系表
                DbSession.R_UserInfo_RoleInfoDal.Add(model);
            }
            DbSession.SaveChanges();

            return true;
        }
    }
}
